﻿using System;
using System.Linq;
using System.Web.Mvc;

namespace UniversityPortal.Models
{
    public class UAuthorizeAttribute:AuthorizeAttribute
    {
        private readonly DataModel.Models.UniversityPortalEntities _entityModel = new DataModel.Models.UniversityPortalEntities();
        public string UserRoles { get; set; }
       
        public override bool Match(object obj)
        {
            return base.Match(obj);
        }

        /// <summary>
        /// User custom authorize attribute
        /// </summary>
        /// <param name="filterContext"></param>
        /// TODO:Roles
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string[] roles = UserRoles.Split(',','.');
            Guid id = Guid.Empty;
            object baseSession = filterContext.RequestContext.HttpContext.Session["userID"] as object;

            if (baseSession != null && Guid.TryParse(baseSession.ToString(), out id))
            {
                DataModel.Models.User user = _entityModel.Users.FirstOrDefault(u => u.ID == id);
                if (user == null || user.Roles.FirstOrDefault(r => roles.FirstOrDefault(R => r.name == R) != null) == null)
                {
                    base.OnAuthorization(filterContext);
                    return;
                }
            }
            else base.OnAuthorization(filterContext);
        }
    }
}